import cv2 as cv
import numpy as np


def thresh_demo(img):
    grey = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    ret, binary = cv.threshold(grey, 90, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
    print("thresh_value:%s" % ret)
    cv.imshow('binary', binary)


def local_demo(img):
    grey = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    binary = cv.adaptiveThreshold(grey,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,17,9)
    cv.imshow('binary', binary)


def custom_demo(img):
    grey = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    h,w = grey.shape[:2]
    array = np.reshape(grey,[1,h*w])
    mean = array.sum() / (h*w)
    print(mean)
    ret,binary = cv.threshold(grey, mean, 255, cv.THRESH_BINARY)
    cv.imshow('binary', binary)


src = cv.imread('lena.jpg', 1)
cv.namedWindow('demo', cv.WINDOW_AUTOSIZE)
cv.imshow('demo', src)
# local_demo(src)
# thresh_demo(src)
custom_demo(src)
cv.waitKey(0)
cv.destroyWindow('demo')
